# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/6/18

library(ggplot2)
library(dplyr)
library(tidyr)
library(tibble)
library(optparse)
library(ggrepel)

createWhenNoExist <- function(f){
    ! dir.exists(f) && dir.create(f)
}

option_list <- list(
make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file"),
make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file")
)
opt <- parse_args(OptionParser(option_list = option_list))

parent <- "./"
createWhenNoExist(parent)

pdf(paste0(parent, "/PCA_Screeplot.pdf"), width = 5, height = 4)

parameterFileName <- paste0(parent, "/PCA_R2.csv")
parameterData <- read.csv(parameterFileName, header = T, stringsAsFactors = F, comment.char = "")

head(parameterData)

lineData <- parameterData %>%
    column_to_rownames("X") %>%
    t() %>%
    as.data.frame() %>%
    select(c("R2")) %>%
    rename(value = R2) %>%
    mutate(value=value*100) %>%
    mutate(sum = cumsum(value)) %>%
    rownames_to_column("index")
lineData

plotData <- lineData %>%
gather("Class", "value", - index)
plotData

labelData <- plotData %>%
    select(- c("Class")) %>%
    as.data.frame() %>%
    unique() %>%
    mutate(label = paste0(value, "%"))

labelData

p <- ggplot(plotData, aes(x = index, y = value)) +
    xlab("PC index") +
    ylab("Variance Explained (%)") +
    ggtitle("Scree plot") +
    theme_bw(base_size = 8.8, base_family = "Times") +
    theme(axis.text.x = element_text(size = 9, vjust = 0.5),
    axis.text.y = element_text(size = 8.8), legend.position = 'none',
    axis.title.y = element_text(size = 11), legend.margin = margin(t = 0.3, b = 0.1, unit = 'cm'),
    legend.text = element_text(size = 6), axis.title.x = element_text(size = 11),
    panel.grid.major.y = element_blank(), panel.grid.minor.x = element_blank(), panel.grid.minor.y = element_blank(),
    plot.title = element_text(hjust = 0.5, size = 13)
    ) +
    geom_line(aes(x = index, y = value, group = 1), lineData, size = 0.5, linetype = 1, color = "blue") +
    geom_line(aes(x = index, y = sum, group = 1), lineData, size = 0.5, linetype = 1, color = "green") +
    geom_point(size = 2, pch = 21, color = "red") +
    geom_text_repel(segment.size=0.2,data = labelData, aes(x = index, y = value, label = label), color = "black", size = 2, family = "Times")

p
dev.off()
